package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.PPTInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class PPT_Test_Activity extends AppCompatActivity {
    private static final String TAG = "PPT_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    TextView tV_PPT_Info, tV_PPT1_Set, tV_PPT2_Set, tV_PPT3_Set, tV_PPT4_Set;
    Button btn_PPT_Pass, btn_PPT_Fail, btn_PPT_All_OnOff;
    SeekBar seekBar_PPT1, seekBar_PPT2, seekBar_PPT3, seekBar_PPT4;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;

    boolean is_PPT_All_On = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_ppt_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        initCerebellumManager();
        seekBar_PPT1 = findViewById(R.id.seekBar_PPT1);
        seekBar_PPT2 = findViewById(R.id.seekBar_PPT2);
        seekBar_PPT3 = findViewById(R.id.seekBar_PPT3);
        seekBar_PPT4 = findViewById(R.id.seekBar_PPT4);
        tV_PPT1_Set = findViewById(R.id.tV_PPT1_Set);
        tV_PPT2_Set = findViewById(R.id.tV_PPT2_Set);
        tV_PPT3_Set = findViewById(R.id.tV_PPT3_Set);
        tV_PPT4_Set = findViewById(R.id.tV_PPT4_Set);
        tV_PPT_Info = findViewById(R.id.tV_PPT_Info);

        Factory_PPT_SB(1, seekBar_PPT1, tV_PPT1_Set);
        Factory_PPT_SB(2, seekBar_PPT2, tV_PPT2_Set);
        Factory_PPT_SB(3, seekBar_PPT3, tV_PPT3_Set);
        Factory_PPT_SB(4, seekBar_PPT4, tV_PPT4_Set);
        Factory_PPT_BTN();
        Refresh_Status_Task_Init();
    }

    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }
    private void Factory_PPT_BTN(){
        btn_PPT_Pass = findViewById(R.id.btn_PPT_Pass);
        btn_PPT_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("PPT","通过");
                if(editor.commit()){
                    Toast.makeText(PPT_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(PPT_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(PPT_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_PPT_Fail = findViewById(R.id.btn_PPT_Fail);
        btn_PPT_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("PPT","未通过");
                if(editor.commit()){
                    Toast.makeText(PPT_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(PPT_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(PPT_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_PPT_All_OnOff = findViewById(R.id.btn_PPT_All_OnOff);
        btn_PPT_All_OnOff.setText("推进器全部开");
        btn_PPT_All_OnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(is_PPT_All_On){
                    btn_PPT_All_OnOff.setText("推进器全部开");
                    for (int i=1; i<5; i++){
                        if(!SetPPT(i, 0)){
                            Toast.makeText(PPT_Test_Activity.this, "PPT"+i+"设定失败", Toast.LENGTH_SHORT).show();
                        };
                    }
                }else{
                    btn_PPT_All_OnOff.setText("推进器全部关");
                    for (int i=1; i<5; i++){
                        if(!SetPPT(i, 100)){
                            Toast.makeText(PPT_Test_Activity.this, "PPT"+i+"设定失败", Toast.LENGTH_SHORT).show();
                        };
                    }
                }
                is_PPT_All_On = !is_PPT_All_On;
            }
        });
    }

    private void Factory_PPT_SB(int num, SeekBar seekBar, TextView textView){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int dutyPersent = 0;
            String textView_str = "推进器"+num+"推进值：";
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                switch (progress){
                    case 0:{
                        dutyPersent = 0;
                        break;
                    }
                    case 1:{
                        dutyPersent = 50;
                        break;
                    }
                    case 2: {
                        dutyPersent = 100;
                        break;
                    }
                    default:
                        break;
                }
                textView_str = "推进器"+num+"推进值："+dutyPersent+"%";
                textView.setText(textView_str);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //Log.d(TAG, "Val:"+rpm_val);
                if(SetPPT(num, dutyPersent)){
                    Toast.makeText(PPT_Test_Activity.this, textView_str+"设定成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(PPT_Test_Activity.this, textView_str+"设定失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 2000);
                if(!Refresh_PPT_Status(tV_PPT_Info)){
                    Toast.makeText(PPT_Test_Activity.this, "刷新失败", Toast.LENGTH_SHORT).show();
                }
                //Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }

    private boolean SetPPT(int num, int dutyPersent) throws ProtocolException {
        try {
            PPTInfo pptInfo = new PPTInfo();
            pptInfo.setOrder(num);
            pptInfo.setPower(dutyPersent);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            setter.setPPTInfo(pptInfo);
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private int GetPPT(int num) throws ProtocolException {
        PPTInfo pptInfo = null;
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            pptInfo = getter.getPPTInfo(num);
            return pptInfo.getPower();
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return -1;
    }

    private boolean Refresh_PPT_Status(TextView tV){
        String ppt_info_str = "电力推进器1~4：";
        boolean ret = true;
        int dutyPersent = 0;
        for(int i=1; i<5 ; i++){
            dutyPersent = GetPPT(i);
            if(dutyPersent == -1){
                ppt_info_str = ppt_info_str.concat("失败，");
                ret = false;
            }else{
                ppt_info_str = ppt_info_str.concat(dutyPersent+"%，");
            }
        }
        tV.setText(ppt_info_str);
        return ret;
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(PPT_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(PPT_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}